<template>
  <div>
    <basic-container>
      <el-row style="margin-bottom: 20px">
        <el-tabs type="border-card" class="informationLabel">
          <el-tab-pane label="前加工作业搜索">
            <!-- <el-col :span="15"> -->
            <avue-form ref="searchForm" v-model="searchForm" :option="searchOption" @reset-change="emptytSearch" @submit="searchSubmit"></avue-form>
            <!-- </el-col> -->
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-tabs type="border-card" class="informationLabel">
            <el-tab-pane label="前加工作业明细">
              <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>作业</h3>
              <div style="display: flex; justify-content: space-between">
                <div class="taskIndex">
                  <div>工单计划产品数量</div>
                  <div>{{ workOrderPlanQuantity }}</div>
                </div>
                <div class="taskIndex">
                  <div>前加工物料数量</div>
                  <div>{{ totalPartQuantity }}</div>
                </div>
                <div class="taskIndex">
                  <div>已加工物料数量</div>
                  <div>{{ processedPartQuantity }}</div>
                </div>
              </div>
              <el-row :gutter="20">
                <el-col :span="8">
                  <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>操作区</h3>
                  <avue-form ref="operationAreaInfo" v-model="operationAreaInfo" :option="operationAreaOption" @reset-change="emptytChange">
                    <template slot="packNo">
                      <el-input
                        placeholder="请扫描 包装条码"
                        name="packNo"
                        v-model="operationAreaInfo.packNo"
                        :clearable="true"
                        suffix-icon="iconfont iconicon_scan"
                        @keyup.enter.native="scanPacking"
                      >
                      </el-input>
                    </template>
                  </avue-form>
                  <div style="width: 100%; text-align: center">
                    <el-button type="primary" size="small" @click="viewSop">查看SOP</el-button>
                    <el-button type="success" size="small" @click="submit" :disabled="isDisabled">完工</el-button>
                  </div>
                </el-col>
                <el-col :span="16">
                  <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>物料信息</h3>
                  <avue-crud :option="partInfoOption" :data="partInfoData" :row-class-name="tableRowClassName" ref="crud" @selection-change="selectionChange">
                    <template slot-scope="{ row }" slot="menu">
                      <el-button type="text" icon="el-icon-view" size="small" @click.stop="handleView(row)">包装明细</el-button>
                    </template>
                  </avue-crud>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
      <el-dialog class="showEsopDialog" v-dragDirectives ref="dialog" title="查看SOP" append-to-body :visible.sync="showEsopDialog" :close-on-click-modal="false" top="5vh">
        <iframe ref="pdf" :src="esopUrl" width="100%" height="100%"></iframe>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="showEsopDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
        </span>
      </el-dialog>
      <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    </basic-container>
  </div>
</template>

<script>
import repairDetail from '@/components/repair/detail.vue';
import { getList, scanPack, finish } from '@/api/product/preProcessingTasks.js';
import { getRoutesByWo } from '@/api/product/part-lock';
import website from '@/config/website';
import { getToken } from '@/util/auth';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { Base64 } from 'js-base64';
import { downLoad } from '@/api/resource/attach';
import { selectInput } from '@/util/helpers';

export default {
  name: 'RepairRepairOut',
  components: {
    repairDetail,
    userTableConfig,
    CommonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    return {
      search: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      searchForm: {},
      searchOption: {
        submitBtn: true,
        submitText: '搜索',
        emptyBtn: true,
        emptyText: '清空',
        labelWidth: 115,
        menuPosition: 'right',
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            span: 6,
            type: 'search',
            disabled: true,
            placeholder: '请选择 工单号',
            rules: [
              {
                required: true,
                message: '请选择 工单号',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openCommonModal();
            }
          },
          {
            label: '产品编码',
            prop: 'partNo',
            span: 6,
            disabled: true
          },
          {
            label: '产品名称',
            prop: 'partName',
            span: 6,
            disabled: true
          },
          {
            label: '产品型号',
            prop: 'partModel',
            span: 6,
            disabled: true
          }
        ]
      },
      operationAreaOption: {
        submitBtn: false,
        emptyBtn: false,
        // submitText: '收料',
        column: [
          {
            label: '包装条码',
            prop: 'packNo',
            span: 24,
            placeholder: '请扫描 包装条码',
            formslot: true,
            rules: [
              {
                required: true,
                message: '请扫描包装条码',
                trigger: 'submit'
              }
            ]
          },
          {
            label: '物料编码',
            span: 24,
            prop: 'partNo',
            disabled: true
          },
          {
            label: '加工规则',
            span: 24,
            prop: 'processRule',
            disabled: true
          }
        ]
      },
      operationAreaInfo: {},
      tableOption: {},
      partInfoOption: {
        height: 375,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false,
        selection: false,
        dialogClickModal: false,
        menu: true,
        labelWidth: 120,
        // cellBtn: true,
        delBtn: false,
        column: [
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '应加工数量',
            prop: 'needProcessQuantity'
          },
          {
            label: '已加工数量',
            prop: 'processedQuantity'
          },
          {
            label: '已加工包装数',
            prop: 'processedPackQuantity'
          }
        ]
      },
      partInfoData: [],
      timer: new Date().getTime(),
      recordId: '',
      pdfUrl: '',
      esopUrl: '',
      isDisabled: true,
      workOrderPlanQuantity: 0,
      totalPartQuantity: 0,
      processedPartQuantity: 0,
      showEsopDialog: false
    };
  },
  computed: {
    ...mapGetters(['permission']),
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  watch: {},
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    searchSubmit() {
      this.onLoad();
    },
    emptytSearch() {
      this.$refs.searchForm.resetFields();
      this.searchForm = {};
    },
    searchReset() {
      this.query = {};
      this.search.objectType = 'PRODUCT';
      this.onLoad();
    },
    searchChange(params, done) {
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad();
    },
    onLoad() {
      this.loading = true;
      getList({ partNo: this.operationAreaInfo.partNo, workOrderId: this.searchForm.workOrderId }).then((res) => {
        this.partInfoData = this._get(res, 'data.data.items', []);
        this.recordId = this._get(res, 'data.data.recordId', '');
        this.workOrderPlanQuantity = this._get(res, 'data.data.workOrderPlanQuantity', 0);
        this.totalPartQuantity = this._get(res, 'data.data.totalPartQuantity', 0);
        this.processedPartQuantity = this._get(res, 'data.data.processedPartQuantity', 0);
        this.pdfUrl = this._get(res, 'data.data.attachUrl', '');
        this.loading = false;
        this.selectionClear();
        this.isDisabled = false;
        this._forEach(this.partInfoData, (item) => {
          if (Number(item.processedQuantity) == 0) {
            this.isDisabled = true;
          }
        });
      });
    },
    /**
     * 打开选择工单号模态框
     */
    openCommonModal() {
      let url = '/api/mes-product/preprocess/record/query-workorder';
      this.modalName = 'workorderModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: url,
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true,
            searchType: 'input',
            type: 'search'
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select',
            rules: [
              {
                required: true,
                message: '请选择工单类型',
                trigger: 'change'
              }
            ],
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity',
            type: 'number',
            minRows: 1
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true,
            searchType: 'input',
            type: 'search'
          },
          {
            label: '产品名称',
            prop: 'partName',
            search: true
          },
          {
            label: '派工产线',
            prop: 'productionLineNames',
            searchType: 'input',
            type: 'search'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '状态',
            prop: 'statusDesc'
          },
          {
            label: '是否配置工艺路线',
            prop: 'routeConfigured',
            type: 'select',
            search: true,
            searchSpan: 8,
            searchLabelWidth: 135,
            dicData: [
              {
                label: '是',
                value: true
              },
              {
                label: '否',
                value: false
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea'
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'workorderModal') {
        this.searchForm.workOrderId = this._get(rowData, 'id', '');
        this.searchForm.workOrderNo = this._get(rowData, 'orderNo', '');
        this.searchForm.partNo = this._get(rowData, 'partNo', '');
        this.searchForm.partName = this._get(rowData, 'partName', '');
        this.searchForm.partModel = this._get(rowData, 'partModel', '');
        this.searchSubmit();
      }
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    scanPacking() {
      scanPack({ recordId: this.recordId, packNo: this.operationAreaInfo.packNo }).then(
        (res) => {
          this.$message.success(res.data.msg);
          this.operationAreaInfo.partNo = this._get(res, 'data.data.partNo', '');
          this.operationAreaInfo.processRule = this._get(res, 'data.data.processRule', '');
          this.operationAreaInfo.packNo = '';
          this.onLoad();
        },
        (error) => {
          selectInput('packNo');
        }
      );
    },
    tableRowClassName({ row, rowIndex }) {
      return row.isHighLight == 1 ? 'scan-select-row' : '';
    },
    submit() {
      finish({ recordId: this.recordId }).then((res) => {
        this.$message.success(res.data.msg);
        this.$refs.searchForm.resetFields();
        this.searchForm = {};
        this.$refs.operationAreaInfo.resetFields();
        this.operationAreaInfo = {};
        this.partInfoData = [];
        this.workOrderPlanQuantity = 0;
        this.totalPartQuantity = 0;
        this.processedPartQuantity = 0;
        this.isDisabled = true;
      });
    },
    viewSop() {
      if (!this.pdfUrl || this.pdfUrl == null) {
        this.$message({
          type: 'warning',
          message: '未配置SOP附件，请先配置SOP文件！'
        });
        return;
      }
      this.showEsopDialog = true;
      this.downLoadEsop();
    },
    downLoadEsop() {
      downLoad({ link: this.pdfUrl }).then(
        (res) => {
          // var blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
          let fileURL = null;
          var blob = new Blob([res.data], { type: 'application/pdf' });
          if (window.createObjectURL != undefined) {
            // basic
            fileURL = window.createObjectURL(blob);
          } else if (window.webkitURL != undefined) {
            // webkit or chrome
            try {
              fileURL = window.webkitURL.createObjectURL(blob);
            } catch (error) {
              console.log(error);
            }
          } else if (window.URL != undefined) {
            // mozilla(firefox)
            try {
              fileURL = window.URL.createObjectURL(blob);
            } catch (error) {
              console.log(error);
            }
          }
          this.esopUrl = '/pdf/web/viewer.html?file=' + encodeURIComponent(fileURL);
        },
        (error) => {}
      );
    },
    handleView(row) {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '包装明细',
        url: `/api/mes-product/preprocess/record/detail-packing?partNo=${row.partNo}&recordId=${this.recordId}`,
        isPage: false,
        rowSelectionType: 'single',
        readonly: true,
        columnDefs: [
          {
            label: '包装条码',
            prop: 'packNo'
          },
          {
            label: '数量',
            prop: 'packQuantity'
          }
        ]
      };
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-table {
  margin-bottom: 10px;
}
::v-deep .el-table .scan-select-row {
  background-color: #caf982 !important;
}
.taskIndex {
  width: 32%;
  padding: 10px 0;
  text-align: center;
  border: 1px dashed #dcdcdc;
  font-weight: bold;
}
::v-deep .avue-crud {
  .avue-crud__menu {
    display: none;
  }
}
.showEsopDialog ::v-deep .el-dialog__body {
  height: 76vh;
}
</style>
